# -*- coding: utf-8 -*-
"""
Created on Fri Jul  7 09:06:36 2017

@author: WANGWEIW23
"""
from PIL import Image
import os
import pandas as pd
import numpy as np
from pandas import Series,DataFrame
def eachFile(filepath):
    filelist2=[]
    pathDir = os.listdir(filepath)
    pathDir_pic=[]
    for files in pathDir:
        pathDir_pic.append(os.path.splitext(files)[0])
    for allDir in pathDir:
        child = os.path.join('%s%s%s' % (filepath,'/', allDir))
        filelist2.append(child)
       
    return filelist2,pathDir_pic

def filepath(mainpath="/data02/Images/Images/"):
    path1=os.listdir(mainpath)
    directory1=[]
    for i in range(len(path1)):
        if path1[i][0]!='.':
           directory1.append(os.path.join(mainpath,path1[i]))
    directory2=[]
    for i in range(len(directory1)):
        path2=os.listdir(directory1[i])
        for j in range(len(path2)):
            if path2[j][0]!='.':
               directory2.append(os.path.join(directory1[i],path2[j]))
    picdirec=[]
    for i in range(len(directory2)):
        path3=os.listdir(directory2[i])
        for j in range(len(path3)):
            if path3[j][0]!='.':
               picdirec.append(os.path.join(directory2[i],path3[j]))
    return picdirec 

picdirec=filepath(mainpath="/data02/Images/Images")
indirec=filepath(mainpath="/data02/Frame_Labels/FACS")

def datafile(picdirec):
    x=[]
    for i in range(len(picdirec)):
        try:
            im=Image.open(picdirec[i])
        except:
            continue
        im.load()
        pixes=np.asarray(im,dtype='float32')
        x.append(pixes)
    shape_list=[]
    for i in range(len(x)):
        shape_list.append(x[i].shape)
    global dict
    dict_num=dict((i,shape_list.count(i)) for i in set(shape_list))
    dict=sorted(dict_num.items(),key=lambda d:d[1],reverse=True)
    img_size=dict[0][0]
    x_resized=[]
    for i in range(len(picdirec)):
        try:
            im=Image.open(picdirec[i])
            im=im.resize((img_size[1],img_size[0]))
        except:
            continue
        im.load()
        pixes=np.asarray(im,dtype='float32')
        x_resized.append([picdirec[i].split('/')[6].split('.')[0],pixes])
    return x_resized

def labelfile(indirec):
    num=len(indirec);
    y=np.zeros([num,10])
    y = y.astype(np.str)
    for j in range(num):   
        try:
            f=open(indirec[j])
            lines=f.readlines()
            y[j,0]=indirec[j].split('/')[6].split('_')[0]
            for k in range(len(lines)):
                y[j,2*(k+1)-1]=lines[k].strip().split("   ")[0]
                y[j,2*(k+1)]=lines[k].strip().split("   ")[1]                         
        except:
            continue
    return y
        
